// 性格特征记录表逻辑处理文件

/**
 * 计算性格特征评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估结果
 */
export function calculatePersonalityAssessment(formData) {
  // 计算性格特征得分（第一部分）
  const personalityScores = calculatePersonalityScores(formData);
  
  // 计算精神状态得分（第二部分）
  const mentalStateScores = calculateMentalStateScores(formData);
  
  // 生成评估摘要
  const summary = generateSummary(personalityScores, mentalStateScores);
  
  return {
    personalityScores: personalityScores,
    mentalStateScores: mentalStateScores,
    summary: summary,
    completeness: calculateCompleteness(formData)
  };
}

/**
 * 计算性格特征得分
 * @param {Object} formData - 表单数据
 * @returns {Object} 性格特征得分
 */
function calculatePersonalityScores(formData) {
  const personalityQuestions = [
    'PT01', 'PT02', 'PT03', 'PT04', 'PT05',
    'PT06', 'PT07', 'PT08', 'PT09', 'PT10'
  ];
  
  const scores = {};
  let totalScore = 0;
  let answeredCount = 0;
  
  personalityQuestions.forEach(qId => {
    const value = formData[qId];
    if (value !== undefined && value !== null && value !== '') {
      scores[qId] = parseInt(value);
      totalScore += parseInt(value);
      answeredCount++;
    } else {
      scores[qId] = null;
    }
  });
  
  const averageScore = answeredCount > 0 ? (totalScore / answeredCount) : 0;
  
  return {
    scores: scores,
    totalScore: totalScore,
    averageScore: averageScore.toFixed(2),
    answeredCount: answeredCount,
    totalQuestions: personalityQuestions.length,
    completeness: ((answeredCount / personalityQuestions.length) * 100).toFixed(1)
  };
}

/**
 * 计算精神状态得分
 * @param {Object} formData - 表单数据
 * @returns {Object} 精神状态得分
 */
function calculateMentalStateScores(formData) {
  const mentalStateQuestions = [
    'MS01', 'MS02', 'MS03', 'MS04', 'MS05', 'MS06', 'MS07', 'MS08', 'MS09', 'MS10',
    'MS11', 'MS12', 'MS13', 'MS14', 'MS15', 'MS16', 'MS17', 'MS18', 'MS19', 'MS20', 'MS21'
  ];
  
  const scores = {};
  let totalScore = 0;
  let answeredCount = 0;
  
  // 焦虑相关题目（通常包括：MS01, MS02, MS04, MS06, MS07, MS08, MS09, MS11, MS12, MS14, MS15, MS18, MS19, MS20）
  const anxietyQuestions = ['MS01', 'MS02', 'MS04', 'MS06', 'MS07', 'MS08', 'MS09', 'MS11', 'MS12', 'MS14', 'MS15', 'MS18', 'MS19', 'MS20'];
  let anxietyScore = 0;
  let anxietyCount = 0;
  
  // 抑郁相关题目（通常包括：MS03, MS05, MS10, MS13, MS16, MS17, MS21）
  const depressionQuestions = ['MS03', 'MS05', 'MS10', 'MS13', 'MS16', 'MS17', 'MS21'];
  let depressionScore = 0;
  let depressionCount = 0;
  
  mentalStateQuestions.forEach(qId => {
    const value = formData[qId];
    if (value !== undefined && value !== null && value !== '') {
      const score = parseInt(value);
      scores[qId] = score;
      totalScore += score;
      answeredCount++;
      
      // 计算焦虑得分
      if (anxietyQuestions.includes(qId)) {
        anxietyScore += score;
        anxietyCount++;
      }
      
      // 计算抑郁得分
      if (depressionQuestions.includes(qId)) {
        depressionScore += score;
        depressionCount++;
      }
    } else {
      scores[qId] = null;
    }
  });
  
  const averageScore = answeredCount > 0 ? (totalScore / answeredCount) : 0;
  const averageAnxietyScore = anxietyCount > 0 ? (anxietyScore / anxietyCount) : 0;
  const averageDepressionScore = depressionCount > 0 ? (depressionScore / depressionCount) : 0;
  
  // 评估焦虑和抑郁程度
  const anxietyLevel = assessAnxietyLevel(averageAnxietyScore);
  const depressionLevel = assessDepressionLevel(averageDepressionScore);
  
  return {
    scores: scores,
    totalScore: totalScore,
    averageScore: averageScore.toFixed(2),
    answeredCount: answeredCount,
    totalQuestions: mentalStateQuestions.length,
    completeness: ((answeredCount / mentalStateQuestions.length) * 100).toFixed(1),
    anxietyScore: {
      total: anxietyScore,
      average: averageAnxietyScore.toFixed(2),
      count: anxietyCount,
      level: anxietyLevel
    },
    depressionScore: {
      total: depressionScore,
      average: averageDepressionScore.toFixed(2),
      count: depressionCount,
      level: depressionLevel
    }
  };
}

/**
 * 评估焦虑程度
 * @param {Number} averageScore - 平均得分
 * @returns {Object} 焦虑程度评估
 */
function assessAnxietyLevel(averageScore) {
  if (averageScore < 0.5) {
    return {
      level: '无焦虑',
      description: '焦虑症状不明显',
      color: '#52c41a'
    };
  } else if (averageScore < 1.0) {
    return {
      level: '轻度焦虑',
      description: '存在轻度焦虑症状，建议关注',
      color: '#faad14'
    };
  } else if (averageScore < 2.0) {
    return {
      level: '中度焦虑',
      description: '存在中度焦虑症状，建议咨询专业医生',
      color: '#ff9800'
    };
  } else {
    return {
      level: '重度焦虑',
      description: '存在重度焦虑症状，强烈建议寻求专业医疗帮助',
      color: '#ff4d4f'
    };
  }
}

/**
 * 评估抑郁程度
 * @param {Number} averageScore - 平均得分
 * @returns {Object} 抑郁程度评估
 */
function assessDepressionLevel(averageScore) {
  if (averageScore < 0.5) {
    return {
      level: '无抑郁',
      description: '抑郁症状不明显',
      color: '#52c41a'
    };
  } else if (averageScore < 1.0) {
    return {
      level: '轻度抑郁',
      description: '存在轻度抑郁症状，建议关注',
      color: '#faad14'
    };
  } else if (averageScore < 2.0) {
    return {
      level: '中度抑郁',
      description: '存在中度抑郁症状，建议咨询专业医生',
      color: '#ff9800'
    };
  } else {
    return {
      level: '重度抑郁',
      description: '存在重度抑郁症状，强烈建议寻求专业医疗帮助',
      color: '#ff4d4f'
    };
  }
}

/**
 * 计算完整度
 * @param {Object} formData - 表单数据
 * @returns {Object} 完整度信息
 */
function calculateCompleteness(formData) {
  const requiredFields = ['patientName', 'age', 'gender', 'recordTime'];
  const personalityQuestions = ['PT01', 'PT02', 'PT03', 'PT04', 'PT05', 'PT06', 'PT07', 'PT08', 'PT09', 'PT10'];
  const mentalStateQuestions = ['MS01', 'MS02', 'MS03', 'MS04', 'MS05', 'MS06', 'MS07', 'MS08', 'MS09', 'MS10', 'MS11', 'MS12', 'MS13', 'MS14', 'MS15', 'MS16', 'MS17', 'MS18', 'MS19', 'MS20', 'MS21'];
  
  let requiredCount = 0;
  let personalityCount = 0;
  let mentalStateCount = 0;
  
  requiredFields.forEach(field => {
    if (formData[field] && formData[field] !== '') {
      requiredCount++;
    }
  });
  
  personalityQuestions.forEach(qId => {
    if (formData[qId] !== undefined && formData[qId] !== null && formData[qId] !== '') {
      personalityCount++;
    }
  });
  
  mentalStateQuestions.forEach(qId => {
    if (formData[qId] !== undefined && formData[qId] !== null && formData[qId] !== '') {
      mentalStateCount++;
    }
  });
  
  const totalRequired = requiredFields.length + personalityQuestions.length + mentalStateQuestions.length;
  const totalAnswered = requiredCount + personalityCount + mentalStateCount;
  const completeness = (totalAnswered / totalRequired) * 100;
  
  return {
    required: {
      filled: requiredCount,
      total: requiredFields.length,
      percentage: ((requiredCount / requiredFields.length) * 100).toFixed(1)
    },
    personality: {
      filled: personalityCount,
      total: personalityQuestions.length,
      percentage: ((personalityCount / personalityQuestions.length) * 100).toFixed(1)
    },
    mentalState: {
      filled: mentalStateCount,
      total: mentalStateQuestions.length,
      percentage: ((mentalStateCount / mentalStateQuestions.length) * 100).toFixed(1)
    },
    total: {
      filled: totalAnswered,
      total: totalRequired,
      percentage: completeness.toFixed(1)
    }
  };
}

/**
 * 生成评估摘要
 * @param {Object} personalityScores - 性格特征得分
 * @param {Object} mentalStateScores - 精神状态得分
 * @returns {String} 摘要文本
 */
function generateSummary(personalityScores, mentalStateScores) {
  let summary = '=== 性格特征评估结果 ===\n';
  summary += `总得分：${personalityScores.totalScore} 分\n`;
  summary += `平均得分：${personalityScores.averageScore} 分\n`;
  summary += `完成度：${personalityScores.completeness}%\n\n`;
  
  summary += '=== 精神状态评估结果 ===\n';
  summary += `总得分：${mentalStateScores.totalScore} 分\n`;
  summary += `平均得分：${mentalStateScores.averageScore} 分\n`;
  summary += `完成度：${mentalStateScores.completeness}%\n\n`;
  
  summary += '=== 焦虑评估 ===\n';
  summary += `焦虑得分：${mentalStateScores.anxietyScore.total} 分（平均：${mentalStateScores.anxietyScore.average} 分）\n`;
  summary += `焦虑程度：${mentalStateScores.anxietyScore.level.level}\n`;
  summary += `${mentalStateScores.anxietyScore.level.description}\n\n`;
  
  summary += '=== 抑郁评估 ===\n';
  summary += `抑郁得分：${mentalStateScores.depressionScore.total} 分（平均：${mentalStateScores.depressionScore.average} 分）\n`;
  summary += `抑郁程度：${mentalStateScores.depressionScore.level.level}\n`;
  summary += `${mentalStateScores.depressionScore.level.description}\n`;
  
  return summary;
}

/**
 * 验证性格特征表单数据
 * @param {Object} formData - 表单数据
 * @returns {Object} 验证结果
 */
export function validatePersonalityForm(formData) {
  const errors = [];
  const warnings = [];
  
  // 个人信息字段已改为选填，不再进行必填验证
  // 只验证如果填写了年龄，则必须在有效范围内
  if (formData.age !== null && formData.age !== undefined && formData.age !== '') {
    const age = parseInt(formData.age);
    if (isNaN(age) || age < 0 || age > 150) {
      errors.push('年龄应在0-150岁之间');
    }
  }
  
  // 性格特征问题验证
  const personalityQuestions = ['PT01', 'PT02', 'PT03', 'PT04', 'PT05', 'PT06', 'PT07', 'PT08', 'PT09', 'PT10'];
  personalityQuestions.forEach(qId => {
    if (formData[qId] === undefined || formData[qId] === null || formData[qId] === '') {
      errors.push(`性格特征问题 ${qId} 为必填项`);
    }
  });
  
  // 精神状态问题验证
  const mentalStateQuestions = ['MS01', 'MS02', 'MS03', 'MS04', 'MS05', 'MS06', 'MS07', 'MS08', 'MS09', 'MS10', 'MS11', 'MS12', 'MS13', 'MS14', 'MS15', 'MS16', 'MS17', 'MS18', 'MS19', 'MS20', 'MS21'];
  mentalStateQuestions.forEach(qId => {
    if (formData[qId] === undefined || formData[qId] === null || formData[qId] === '') {
      errors.push(`精神状态问题 ${qId} 为必填项`);
    }
  });
  
  return {
    isValid: errors.length === 0,
    errors,
    warnings,
    hasWarnings: warnings.length > 0
  };
}

export default {
  calculatePersonalityAssessment,
  validatePersonalityForm
};

